<?php

declare(strict_types=1);

namespace app\api\controller;

use app\api\controller\Base;
use app\common\model\Advert;
use app\common\model\ProductCate;
use app\common\model\Product;
use app\common\model\User;
use app\common\model\ProductOrder as ProductOrderModel;
use app\common\model\ProductOrderList;
use app\common\model\ProductNorms;
use app\common\model\ProductNormsValue;
use app\common\model\UserAddress;

use \think\Request;

class ProductOrder extends Base
{
    /**
     * 确认订单页面
     */
    public function order_info(Request $request)
    {
        $user = $this->getUser();
        $product_id = $request->param('product_id/d');
        $name = $request->param("name", '');
        $mobile = $request->param("mobile", '');
        $address = $request->param("address", '');
        $buy_num = $request->param('buy_num/d');
        $sku_id = $request->param('sku_id/d');
        $use_money_is = request()->param('use_money_is/d', 0);       #0不抵扣 1抵扣
        $use_integral_is = request()->param('use_integral_is/d', 0); #0不抵扣 1抵扣

        if (empty($product_id)) {
            return $this->renderError("缺少参数");
        }
        if (empty($buy_num) || empty($sku_id)) {
            return $this->renderError("请选择商品数量或规格");
        }

        $w = [];
        $w[] = ['id', '=', $product_id];
        $w[] = ['status', '=', 1];
        $field = "id,title,imgurl,status,yunfei";
        $product = Product::getInfo($w, $field);
        $product['imgurl'] = imageUrl($product['imgurl']);
        $sku = ProductNormsValue::getInfo(['id' => $sku_id, 'product_id' => $product_id], 'sku,price');
        if (empty($sku)) {
            return $this->renderError("参数错误");
        }
        $product['sku'] = $sku['sku'];
        $product['price'] = $sku['price'];
        $product['buy_num'] = $buy_num;
        /***********计算总价格***********/
        $total_price = jisuan($buy_num, $product['price'], '*', '2');
        $total_price = jisuan($total_price, $product['yunfei'], '+', '2'); //订单总价
        #潮币抵扣
        $use_integral = 0;
        $price  =  0;
        $surplus_integral =  $user['integral'];
        $surplus_money = $user['money'];

        if ($use_integral_is == '1') {
            $price = $total_price * 100;
            if ($user['integral'] >= $price) {
                $use_integral = $price;
                $price = 0;
                $surplus_integral = $user['integral'] - $use_integral;
            } else {
                $use_integral = $user['integral'];
                $price = bcsub("$price", "{$user['integral']}", 2);
                $surplus_integral = 0;
            }
            $price = $price / 100;
        } else {
            $price = $total_price;
        }
        #余额抵扣
        $use_money = 0;
        if ($use_money_is == '1') {
            if ($user['money'] >= $price) {
                $use_money = $price;  // 全部使用
                $price = 0;
                $surplus_money = $user['money'] - $price;
            } else {
                $use_money = $user['money']; #
                $price = bcsub("$price", "{$user['money']}", 2);
                $surplus_money = 0;
            }
        }

        /***********计算价格***********/
        $result['price'] = $price;
        $result['total_price'] = $total_price;
        $result['use_integral'] = $use_integral;
        $result['use_money'] = $use_money;

        $result['surplus_integral'] = $surplus_integral;
        $result['surplus_money'] = $surplus_money;
        return $this->renderSuccess("请求成功", compact('result', 'product', 'address'));
    }

    /**
     * 商户订单提交
     */
    public function order_add(Request $request)
    {
        $user = $this->getUser();
        $product_id = $request->param('product_id/d');
        $name = $request->param("name", '');
        $mobile = $request->param("mobile", '');
        $address = $request->param("address", '');
        $message = $request->param("message", '');
        $buy_num = $request->param('buy_num/d');
        $sku_id = $request->param('sku_id/d');
        $use_money_is = $request->param('use_money_is/d', 0);       #0不抵扣 1抵扣
        $use_integral_is = $request->param('use_integral_is/d', 0); #0不抵扣 1抵扣
        $pay_way = request()->param('pay_way');  //支付
        if (empty($product_id)) {
            return $this->renderError("缺少参数");
        }
        if (empty($name) || empty($mobile) || empty($address)) {
            return $this->renderError("缺少收货信息");
        }
        if (empty($buy_num) || empty($sku_id)) {
            return $this->renderError("请选择商品数量或规格");
        }
        if ($buy_num < 1) {
            return $this->renderError("请选择商品数量");
        }

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $key = "product_order_add_" . $user['id'];
        $redis_key_info = $redis->get($key);
        if ($redis_key_info) {
            return $this->renderError("当前操作太快了,请等待");
        } else {
            $redis->set($key, 1, 3);
        }
        $w = [];
        $w[] = ['id', '=', $product_id];
        $w[] = ['status', '=', 1];
        $field = "id,title,imgurl,status,yunfei";
        $product = Product::getInfo($w, $field);
        $sku = ProductNormsValue::getInfo(['id' => $sku_id, 'product_id' => $product_id], 'sku,price,stock');
        if (empty($sku)) {
            $redis->del($key);
            return $this->renderError("参数错误");
        }
        if ($sku['stock'] < $buy_num) {
            $redis->del($key);
            return $this->renderError("商品库存不足");
        }
        $product['sku'] = $sku['sku'];
        $product['price'] = $sku['price'];
        /***********计算总价格***********/
        $total_price = jisuan($buy_num, $product['price'], '*', '2');
        $total_price = jisuan($total_price, $product['yunfei'], '+', '2'); //订单总价
        #潮币抵扣
        $use_integral = 0;
        // if ($use_integral_is == 1) {
        //     $price = $total_price * 100;
        //     if ($user['integral'] >= $price) {
        //         $use_integral = $price;
        //         $price = 0;
        //     } else {
        //         $use_integral = $user['integral'];
        //         $price = bcsub("$price", "{$user['integral']}", 2);
        //     }
        //     $price = $price / 100;
        // }
        #余额抵扣
        $price = $total_price;

        $use_money = 0;
        if ($use_money_is == 1) {
            if ($user['money'] >= $price) {
                $use_money = $price;  // 全部使用
                $price = 0;
            } else {
                $use_money = $user['money']; #
                $price = bcsub("$price", "{$user['money']}", 2);
            }
        }


        $total = $price;
        /***********计算价格***********/
        $order_num = create_order_no('SC_', 'product_order', 'order_num');
        $arr = [];
        $arr['user_id'] = $user['id'];
        $arr['order_num'] = $order_num;
        $arr['total'] = $total;
        $arr['total_price'] = $total_price;
        $arr['yunfei'] = $product['yunfei'];
        $arr['status'] = 1;
        $arr['addtime'] = time();
        $arr['pay_type'] = $pay_way == 'ali_wap' ? 2 : 1; #1微信 2支付宝
        $arr['name'] = $name;
        $arr['mobile'] = $mobile;
        $arr['use_integral'] = $use_integral;
        $arr['use_money'] = $use_money;
        $arr['province'] = '';
        $arr['city'] = '';
        $arr['county'] = '';
        $arr['address'] = $address;
        $arr['order_type'] = 1;
        ProductOrderModel::startTrans();
        $dd = ProductOrderModel::insertGetId($arr);
        $row = [];
        $row['order_id'] = $dd;
        $row['order_num'] = $order_num;
        $row['user_id'] = $user['id'];
        $row['product_id'] = $product['id'];
        $row['title'] = $product['title'];
        $row['price'] = $product['price'];
        $row['imgurl'] = $product['imgurl'];
        $row['num'] = $buy_num;
        $row['status'] = 1;
        $row['sku'] = $product['sku'];
        $row['order_type'] = 1;
        $row['addtime'] = time();
        $pp = ProductOrderList::insert($row);
        /***********减少商品库存************/
        $nn = $mm = 1;
        // $nn = ProductNormsValue::where(['id' => $sku_id])->dec('stock', $buy_num)->update();
        // $mm = Product::where(['id' => $product_id])->dec('stock', $buy_num)->inc('sales', $buy_num)->update();
        /***********减少商品库存************/
        if ($pp && $dd && $mm && $nn) {
            ProductOrderModel::commit();
            if ($total > 0) {
                $body = '购买商城商品' . $product['title'];
                $attach = 'product_order';
                if ($pay_way == 'ali_wap') {
                    $payRes = (new Pay())->zfpay($order_num, $total, $body, $attach . ',' . $user['openid']);
                } else {
                    $payRes = (new Pay())->wxCreateOrder($order_num, $total, $user['openid'], $body, $attach);
                }
                if ($payRes['status'] == 1) {
                    #结果集
                    $new_data = [
                        'status' => 1,
                        'order_num' => $order_num,
                        'order_id' => $dd,
                        'res' => $payRes['data'],
                    ];
                    $redis->del($key);
                    return $this->renderSuccess("下单成功", $new_data);
                } else {
                    #删除redis
                    $redis->del($key);
                    ProductOrderModel::rollback();
                    return $this->renderError("下单失败");
                }
            } else {
                $notify = new \app\api\controller\Notify($this->app);
                $data = $notify->update_product_order($order_num);
                if ($data == 1) {
                    $return = [];
                    $return['status'] = 2;
                    $return['order_num'] = $order_num;
                    $return['order_id'] = $dd;
                    $redis->del($key);
                    return $this->renderSuccess("请求成功", $return);
                } else {
                    return $data;
                }
            }
        } else {
            ProductOrderModel::rollback();
            return $this->renderError($pp . $nn . "网络故障，请稍后重试" . $dd . $mm);
        }
    }

    /**
     * 订单支付取消
     */
    public function order_cancel_pay(Request $request)
    {
        $user = $this->getUser();
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $key = "product_order_add_" . $user['id'];
        $redis_key_info = $redis->get($key);
        if ($redis_key_info) {
            $redis->del($key);
        }
        return $this->renderSuccess("请求成功");
    }

    /**
     * 获取订单
     */
    public function get_order(Request $request)
    {
        $order_num = request()->param('order_num', '');
        $w = [];
        $w[] = ['order_num', '=', $order_num];
        $w[] = ['status', '=', 2];
        $field = "id,order_num,total_price,addtime,status,total,order_type";
        $product = ProductOrderModel::getInfo($w, $field);
        return $this->renderSuccess("请求成功",compact('product'));
    }

    /**
     * 我的订单
     */
    public function order_list(Request $request)
    {
        $user = $this->getUser();
        $type = $request->param("type/d", '1');
        $w = [];
        if ($type == 1) {
            //全部
            $w[] = ['status', 'between', [2, 5]];
        } elseif ($type == 2) {
            // 待支付
            $w[] = ['status', '=', '1'];
        } elseif ($type == 3) {
            // 待发货
            $w[] = ['status', '=', '2'];
        } elseif ($type == 4) {
            // 已发货，待收货
            $w[] = ['status', '=', '3'];
        } elseif ($type == 5) {
            // 已收货
            $w[] = ['status', '=', '4'];
        }
        $w[] = ['user_id', '=', $user['id']];
        $order = "id desc";
        $field = "id,order_num,total_price,addtime,status,total,order_type";
        $order = ProductOrderModel::getList($w, $field, $order, $this->page);
        foreach ($order['list'] as $k => &$v) {
            $w = [];
            $w[] = ['order_id', '=', $v['id']];
            $order_list = ProductOrderList::getInfo($w, 'id,product_id,title,price,num,imgurl,sku,order_type');
            $count = 0;
            $order_list['imgurl'] = imageUrl($order_list['imgurl']);
            if ($order_list['order_type'] == 1) {
                $sku_arr = explode(',', trim($order_list['sku'], ','));
                $sku_count = count($sku_arr);
                $norms_count = ProductNorms::where(['product_id' => $order_list['product_id']])->count();
                $attr_sku = [];
                foreach ($sku_arr as $key => $val) {
                    $w = [];
                    $w[] = ['product_id', '=', $order_list['product_id']];
                    $w[] = ['norms_values', 'like', '%' . $val . '%'];
                    $norms_name = ProductNorms::where($w)->value("norms_name");
                    $attr_sku[$key] = $norms_name . '：' . $val;
                }
                $v['sku'] = $attr_sku;
            }
            $count += $order_list['num'];

            $v['goods_count'] = $count;
            $v['order_list'] = $order_list;
            $v['addtime'] = date("Y-m-d H:i:s", $v['addtime']);
        }
        return $this->renderSuccess("请求成功", compact('order'));
    }

    /**
     * 订单详情
     */
    public function order_detail(Request $request)
    {
        $user = $this->getUser();
        $order_id = $request->param('order_id/d');
        $w = [];
        $w[] = ['id', '=', $order_id];
        $w[] = ['user_id', '=', $user['id']];
        $field = "id,order_num,status,total,total_price,order_type,stone,yunfei,addtime,pay_time,pay_type,fa_time,name,mobile,province,city,county,address,courier_number,courier_name";
        $order = ProductOrderModel::getInfo($w, $field);
        $order['addtime'] = date("Y-m-d H:i:s", $order['addtime']);
        $order['order_id'] = $order['id'];
        $w = [];
        $w[] = ['order_id', '=', $order_id];
        $order_list = ProductOrderList::getInfo($w, 'id,product_id,title,imgurl,price,num,sku,order_type');
        $goods_count = $total_goods_price = 0;
        $total_goods_price += $order_list['num'] * $order_list['price'];
        $order_list['imgurl'] = imageUrl($order_list['imgurl']);
        $sku_arr = explode(',', trim($order_list['sku'], ','));
        $sku_count = count($sku_arr);
        $norms_count = ProductNorms::where(['product_id' => $order_list['product_id']])->count();
        $attr_sku = [];
        foreach ($sku_arr as $key => $val) {
            $w = [];
            $w[] = ['product_id', '=', $order_list['product_id']];
            $w[] = ['norms_values', 'like', '%' . $val . '%'];
            $norms_name = ProductNorms::where($w)->value("norms_name");
            $attr_sku[$key] = $norms_name . '：' . $val;
        }
        $order_list['sku'] = $attr_sku;
        $goods_count += $order_list['num'];
        $order['total_goods_price'] = $total_goods_price;
        $order['goods_count'] = $goods_count;
        $order['order_list'] = $order_list;
        return $this->renderSuccess("请求成功", compact('order'));
    }

    /**
     * 确认收货
     */
    public function order_over(Request $request)
    {
        $user = $this->getUser();
        $order_id = $request->param("order_id/d");
        $w = [];
        $w[] = ['id', '=', $order_id];
        $w[] = ['user_id', '=', $user['id']];
        $order = ProductOrderModel::getInfo($w, '*');
        if ($order['status'] != 3) {
            return $this->renderError("该订单暂不能确认收货");
        }
        ProductOrderModel::startTrans();
        $ss = ProductOrderModel::where($w)->update(['status' => '4']);
        $w = [];
        $w[] = ['order_id', '=', $order_id];
        $w[] = ['user_id', '=', $user['id']];
        $dd = ProductOrderList::where($w)->update(['status' => '4']);
        if ($ss && $dd) {
            ProductOrderModel::commit();
            return $this->renderSuccess("确认收货成功");
        } else {
            ProductOrderModel::rollback();
            return $this->renderError("网络故障，请稍后重试");
        }
    }

    /**
     * 物流详情
     */
    public function express_detail(Request $request)
    {
        $order_id = $request->param("order_id/d");
        if (empty($order_id)) {
            return $this->renderError("缺少必要参数");
        }
        $user = $this->getUser();
        //发货订单物流信息
        $whe[] = ['user_id', '=', $user['id']];
        $whe[] = ['id', '=', $order_id];
        $field = "id,order_num,courier_name,courier_number,status,mobile";
        $order = ProductOrderModel::getInfo($whe, $field);
        if (empty($order)) {
            return $this->renderError("参数错误");
        }
        if ($order['status'] == 2) {
            return $this->renderError("订单暂未发货");
        }
        $orderlist = ProductOrderList::getInfo(['order_id' => $order['id']], 'product_id,title,imgurl,num');
        $order['title'] = $orderlist['title'];
        $order['num'] = $orderlist['num'];
        $order['imgurl'] = imageUrl($orderlist['imgurl']);
        if (empty($order['courier_number'])) {
            return $this->renderError("该订单暂未发货");
        }
        $express = expressWuliu($order['courier_number'], $order['courier_code']);
        if ($express['code'] != '1') {
            $express = [];
        } else {
            $express = $express['msg'];
            $status_name = ['快递收件(揽件)', '在途中', '正在派件', '已签收', '派送失败', '疑难件', '退件签收', '其他'];
            $express['deliverystatus'] = $status_name[$express['deliverystatus']];
            $express['issign'] =  $express['issign'] == 1 ? '已签收' : "未签收";
        }
        return $this->renderSuccess("请求成功", compact("order", 'express'));
    }


    /**
     * 取消订单
     */
    public function order_cancel(Request $request)
    {
        $user = $this->getUser();
        $order_id = $request->param("order_id/d");
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $key = "product_order_add_" . $user['id'];
        $redis_key_info = $redis->get($key);
        if ($redis_key_info) {
            return $this->renderError("当前操作太快了,请等待");
        } else {
            $redis->set($key, 1, 3);
        }

        $w = [];
        $w[] = ['id', '=', $order_id];
        $w[] = ['user_id', '=', $user['id']];
        $order = ProductOrderModel::getInfo($w, '*');
        if ($order['status'] != 1) {
            $redis->del($key);
            return $this->renderError("该订单暂不支持取消");
        }
        ProductOrderModel::startTrans();
        $ss = ProductOrderModel::where($w)->update(['status' => '5']);
        $w = [];
        $w[] = ['order_id', '=', $order_id];
        $w[] = ['user_id', '=', $user['id']];
        $dd = ProductOrderList::where($w)->update(['status' => '5']);
        /******************取消订单增加库存*******************/
        if ($order['order_type'] == 1) {
            //商城订单取消增加库存
            $product = ProductOrderList::getInfo($w, 'id,product_id,sku,num');
            $ww = [];
            $ww[] = ['id', '=', $product['product_id']];
            $pp = Product::where($ww)->inc('stock', $product['num'])->update();
            $ww = [];
            $ww[] = ['product_id', '=', $product['product_id']];
            $ww[] = ['sku', '=', $product['sku']];
            $result = ProductNormsValue::getInfo($ww, 'id,product_id');
            if (!empty($result)) {
                $mm = ProductNormsValue::where($ww)->inc('stock', $product['num'])->update();
            } else {
                $mm = 1;
            }
        }
        /******************取消订单增加库存*******************/
        if ($ss && $dd && $pp && $mm) {
            ProductOrderModel::commit();
            $redis->del($key);
            return $this->renderSuccess("订单取消成功");
        } else {
            ProductOrderModel::rollback();
            $redis->del($key);
            return $this->renderError("网络故障，请稍后重试");
        }
    }


    /**
     * 我的订单立即支付
     */
    public function order_pay(Request $request)
    {
        $user = $this->getUser();
        $order_id = $request->param('order_id/d');
        $pay_type = 1;
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $key = "product_order_pay_" . $user['id'];
        $redis_key_info = $redis->get($key);
        if ($redis_key_info) {
            return $this->renderError("当前操作太快了,请等待");
        } else {
            $redis->set($key, 1, 3);
        }

        $w = [];
        $w[] = ['id', '=', $order_id];
        $w[] = ['user_id', '=', $user['id']];
        $order = ProductOrderModel::getInfo($w, '*');
        if (empty($order)) {
            $redis->del($key);
            return $this->renderError("参数错误");
        }
        if ($order['status'] != 1) {
            $redis->del($key);
            return $this->renderError("该订单暂已支付");
        }
        // $t = time() - 1700;
        // if ($order['addtime'] < $t) {
        //     $redis->del($key);
        //     return $this->renderError("该订单暂不能支付");
        // }
        if ($user['use_integral'] < $order['integral']) {
            $redis->del($key);
            return $this->renderError("您的赏币不足，请重新下单");
        }
        if ($user['use_money'] < $order['money']) {
            $redis->del($key);
            return $this->renderError("您的余额不足，请重新下单");
        }
        $order_num = create_order_no('SC_', 'product_order', 'order_num');
        $row = [];
        $row['order_num'] = $order_num;
        ProductOrderModel::startTrans();
        $dd = ProductOrderModel::where($w)->update($row);
        $ss = ProductOrderList::where(['order_id' => $order_id])->update(['order_num' => $order_num]);
        if ($dd && $ss) {
            $body = '购买商城商品';
            $attach = 'product_order';
            $payRes = (new Pay())->wxCreateOrder($order_num, $order['total'], $user['openid'], $body, $attach);
            if ($payRes['status'] == 1) {
                #结果集
                $new_data = [
                    'status' => 1,
                    'order_num' => $order_num,
                    'order_id' => $dd,
                    'res' => $payRes['data'],
                ];
                $redis->del($key);
                return $this->renderSuccess("支付成功", $new_data);
            } else {
                #删除redis
                $redis->del($key);
                ProductOrderModel::rollback();
                return $this->renderError("支付失败");
            }
        } else {
            ProductOrderModel::rollback();
            $redis->del($key);
            return $this->renderError("网络故障，请稍后重试");
        }
    }
}
